package cn.ycl.system.biz.delivery.service.impl;

import cn.ycl.auth.api.user.feign.RemoteUserService;
import cn.ycl.entity.UserInfoVO;
import cn.ycl.system.biz.delivery.dao.DeliveryAddressDao;
import cn.ycl.system.biz.delivery.entity.DeliveryAddress;
import cn.ycl.system.biz.delivery.service.DeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * (DeliveryAddress)表服务实现类
 *
 * @author yuanchangliang
 * @since 2021-10-19 10:24:57
 */
@Service("deliveryAddressService")
public class DeliveryAddressServiceImpl implements DeliveryAddressService {
    @Resource
    private DeliveryAddressDao deliveryAddressDao;
    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public DeliveryAddress queryById(Long id) {
        return this.deliveryAddressDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<DeliveryAddress> getAddressList() {
        UserInfoVO userInfo = remoteUserService.getUserInfo();
        List<DeliveryAddress> addressList = deliveryAddressDao.getAddressList(userInfo.getUserId());
        int index = 0;
        for (int i = 0; i < addressList.size(); i++) {
            if (addressList.get(i).getDefaultAddress()) {
                index = i;
            }
        }
        //默认配送地址放在首位
        if (index != 0) {
            Collections.swap(addressList, 0, index);
        }
        return addressList;
    }

    /**
     * 新增数据
     *
     * @param deliveryAddress 实例对象
     * @return 实例对象
     */
    @Override
    public DeliveryAddress insert(DeliveryAddress deliveryAddress) {
        this.deliveryAddressDao.insert(deliveryAddress);
        return deliveryAddress;
    }

    /**
     * 修改数据
     *
     * @param deliveryAddress 实例对象
     * @return 实例对象
     */
    @Override
    public DeliveryAddress update(DeliveryAddress deliveryAddress) {
        this.deliveryAddressDao.update(deliveryAddress);
        return this.queryById(deliveryAddress.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.deliveryAddressDao.deleteById(id) > 0;
    }
}
